#include "MainWindow.h"
#include "./ui_MainWindow.h"
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include "CBaseImage.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowIcon(QIcon(":/res/ladybug.ico"));

    m_listModel = new QStringListModel(this);
    ui->listView->setModel(m_listModel);
    ui->listView->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked);


    connect(ui->btn_openFiles, &QPushButton::clicked, this, &MainWindow::onOpenFiles);
    connect(ui->btn_openDir, &QPushButton::clicked, this, &MainWindow::onOpenDir);
    connect(ui->btn_Clear, &QPushButton::clicked, this, &MainWindow::onClear);

    connect(ui->btn_Prev, &QPushButton::clicked, this, &MainWindow::onPrevFile);
    connect(ui->btn_Next, &QPushButton::clicked, this, &MainWindow::onNextFile);
    connect(ui->btn_PrevFrame, &QPushButton::clicked, this, &MainWindow::onPrevFrame);
    connect(ui->btn_NextFrame, &QPushButton::clicked, this, &MainWindow::onNextFrame);

    connect(ui->btn_ToJpg, &QPushButton::clicked, this, &MainWindow::onToJpg);
    connect(ui->btn_ToPng, &QPushButton::clicked, this, &MainWindow::onToPng);
    connect(ui->btn_ToBmp, &QPushButton::clicked, this, &MainWindow::onToBmp);
    connect(ui->btn_ToTiff, &QPushButton::clicked, this, &MainWindow::onToTiff);
    connect(ui->btn_ToVideo, &QPushButton::clicked, this, &MainWindow::onToVideo);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::EnumFiles(QString dirPath, QStringList &vec)
{
    QDir dir(dirPath);
    dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
    dir.setSorting(QDir::Name|QDir::DirsFirst);
    QFileInfoList fList = dir.entryInfoList();
    for (int i=0; i<fList.count(); i++) {
        QFileInfo info = fList[i];
        if (info.isFile())
        {
            QString ext = info.suffix();
            if (ext.compare("dcm", Qt::CaseInsensitive)==0
               || ext.compare("dic", Qt::CaseInsensitive)==0)
            {
                vec.push_back(info.filePath());
            }
        } else if (info.isDir()) {
            EnumFiles(info.filePath(), vec);
        }
    }
}

void MainWindow::onOpenFiles()
{
    QStringList fList = QFileDialog::getOpenFileNames(this, tr("Open Images"), "", tr("Dicom Files (*.dcm *.dic)"));
    for (int i=0; i<fList.count(); i++) {
        QString fileName = fList[i];
        m_listModel->insertRow(m_listModel->rowCount());
        QModelIndex index = m_listModel->index(m_listModel->rowCount()-1, 0);
        m_listModel->setData(index, fileName, Qt::DisplayRole);
    }

    QString fileCount;
    fileCount = QString("DICOM文件 数量:%1").arg(m_listModel->rowCount());
    ui->label_Count->setText(fileCount);
}

void MainWindow::onOpenDir()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "", QFileDialog::ShowDirsOnly|QFileDialog::DontResolveSymlinks);
    if (!dir.isEmpty()) {
        QStringList vec;
        EnumFiles(dir, vec);
        for(int i=0; i<vec.size(); i++) {
            QString fileName = vec[i];
            m_listModel->insertRow(m_listModel->rowCount());
            QModelIndex index = m_listModel->index(m_listModel->rowCount()-1, 0);
            m_listModel->setData(index, fileName, Qt::DisplayRole);
        }

        QString fileCount;
        fileCount = QString("DICOM文件 数量:%1").arg(m_listModel->rowCount());
        ui->label_Count->setText(fileCount);
    }
}

void MainWindow::onClear()
{
    m_listModel->removeRows(0, m_listModel->rowCount());
}

void MainWindow::onPrevFile()
{
    QModelIndex index = ui->listView->currentIndex();
    //    qDebug() << "onPrevFile index:" << index;

    int rowIdx = index.row();
    if (rowIdx == -1) {
        index = m_listModel->index(0, 0);
    } else if (rowIdx == 0) {
        return;
    } else {
        index = m_listModel->index(rowIdx - 1, 0);
    }

    ui->listView->setCurrentIndex(index);

    QString fn = m_listModel->data(index).toString();
    ui->displayer->LoadFile(fn);

}

void MainWindow::onNextFile()
{
    QModelIndex index = ui->listView->currentIndex();
    //    qDebug() << "onNextFile index:" << index;

    int rowIdx = index.row();
    int count = m_listModel->rowCount();
    if (rowIdx == -1) {
        index = m_listModel->index(0, 0);
    } else if (rowIdx == count - 1) {
        return;
    } else {
        index = m_listModel->index(rowIdx + 1, 0);
    }

    ui->listView->setCurrentIndex(index);

    QString fn = m_listModel->data(index).toString();
    ui->displayer->LoadFile(fn);

}

void MainWindow::onPrevFrame()
{
    ui->displayer->PrevFrame();
}

void MainWindow::onNextFrame()
{
    ui->displayer->NextFrame();
}

void MainWindow::onToJpg()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "",
                            QFileDialog::ShowDirsOnly|QFileDialog::DontResolveSymlinks);

    if (!dir.isEmpty()) {
        std::string dst = dir.toStdString();
        if (!ui->displayer->Export(dst, 0)) {
            QMessageBox::critical(this, "错误", "导出JPG失败!");
        }
    }
}

void MainWindow::onToPng()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "",
                            QFileDialog::ShowDirsOnly|QFileDialog::DontResolveSymlinks);

    if (!dir.isEmpty()) {
        std::string dst = dir.toStdString();
        if (!ui->displayer->Export(dst, 1)) {
            QMessageBox::critical(this, "错误", "导出PNG失败!");
        }
    }
}

void MainWindow::onToBmp()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "",
                            QFileDialog::ShowDirsOnly|QFileDialog::DontResolveSymlinks);

    if (!dir.isEmpty()) {
        std::string dst = dir.toStdString();
        if (!ui->displayer->Export(dst, 2)) {
            QMessageBox::critical(this, "错误", "导出BMP失败!");
        }
    }
}

void MainWindow::onToTiff()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "",
                            QFileDialog::ShowDirsOnly|QFileDialog::DontResolveSymlinks);

    if (!dir.isEmpty()) {
        std::string dst = dir.toStdString();
        if (!ui->displayer->Export(dst, 3)) {
            QMessageBox::critical(this, "错误", "导出TIFF失败!");
        }
    }
}

void MainWindow::onToVideo()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "",
                            QFileDialog::ShowDirsOnly|QFileDialog::DontResolveSymlinks);

    if (!dir.isEmpty()) {
        std::string dst = dir.toStdString();
        if (!ui->displayer->Export(dst, 4)) {
            QMessageBox::critical(this, "错误", "导出MP4失败!");
        } else {
            QMessageBox::information(this, "提示", "导出MP4完成!");
        }
    }
}


void MainWindow::on_listView_clicked(const QModelIndex &index)
{
//    qDebug() << "listView clicked at:" << index;
    QString fn = m_listModel->data(index).toString();
    ui->displayer->LoadFile(fn);

    int frames = ui->displayer->GetImage()->GetFrameCount();
    if (frames > 1) {
        ui->btn_NextFrame->setDisabled(false);
        ui->btn_PrevFrame->setDisabled(false);
        ui->btn_ToVideo->setDisabled(false);
    } else {
        ui->btn_NextFrame->setDisabled(true);
        ui->btn_PrevFrame->setDisabled(true);
        ui->btn_ToVideo->setDisabled(true);
    }
}

